package com.software.myopiachildren.utils;

import java.text.DecimalFormat;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author ben.
 * @time 2017/9/28.
 * @description String相关操作的工具类
 */
public class StringUtils {

    // 获取字符串的字符长度   一个中文字=2个字符
    public static int length(String value) {
        int valueLength = 0;
        String chinese = "[\u0391-\uFFE5]";
        /* 获取字段值的长度，如果含中文字符，则每个中文字符长度为2，否则为1 */
        for (int i = 0; i < value.length(); i++) {
            /* 获取一个字符 */
            String temp = value.substring(i, i + 1);
            /* 判断是否为中文字符 */
            if (temp.matches(chinese)) {
                /* 中文字符长度为2 */
                valueLength += 2;
            } else {
                /* 其他字符长度为1 */
                valueLength += 1;
            }
        }
        return valueLength;
    }

    // 获取字符串的字符长度   一个中文字=2个字符
    public static String subStringlength(String value, int len) {
        for (int i = 0; i < value.length(); i++) {
            String temp = value.substring(0, i + 1);
            if (length(temp) > len) {
                return value.substring(0, i);
            }
        }
        return value;
    }

    /**
     * 获取字符串长度，一个中文字符长度为2，一个英文字符为1
     *
     * @param str
     * @return
     */
    public static int getStrLength(String str) {
        if (str == null || str.length() <= 0) {
            return 0;
        }
        int len = 0;

        char[] chars = str.toCharArray();

        for (char c : chars) {
            len += getCharLength(c);
        }

        return len;
    }

    /**
     * 获取字符长度，中文2个，英文1个
     *
     * @param c
     * @return
     */
    public static int getCharLength(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return 2;
        }
        return 1;
    }

    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    /**
     * 验证是不是手机号 (只判断是不是已1开头的11位数)
     *
     * @param mobiles
     * @return
     */

    public static boolean isMobileNO(String mobiles) {
        Pattern p = Pattern.compile("^1\\d{10}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    /**
     * 判断是不是数字
     *
     * @param str
     * @return
     */
    public static boolean isNumeric(String str) {
        if (isEmpty(str)) {
            return false;
        }
        for (int i = str.length(); --i >= 0; ) {
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    /**
     * 判断字符串是否为空
     */
    public static boolean isEmpty(final CharSequence cs) {
        return cs == null || cs.length() == 0;
    }

    /**
     * 获取字符串长度，一个中文字符长度为3，一个英文字符为1
     *
     * @param str
     * @return
     */
    public static int getStrLength_utf8(String str) {
        if (str == null || str.length() <= 0) {
            return 0;
        }
        int len = 0;

        char[] chars = str.toCharArray();

        for (char c : chars) {
            len += getCharLength_utf8(c);
        }

        return len;
    }

    /**
     * 获取字符串长度，一个中文字符长度为3，一个英文字符为1
     *
     * @param c
     * @return
     */
    public static int getCharLength_utf8(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return 3;
        }
        return 1;
    }

    public static boolean isNoEmpty(String s) {
        if (s != null && !s.trim().equals("")) {
            return true;
        } else {
            return false;
        }
    }

    public static String convertFileSize(long size) {
        long kb = 1024;
        long mb = kb * 1024;
        long gb = mb * 1024;

        if (size >= gb) {
            return String.format("%.1f GB", (float) size / gb);
        } else if (size >= mb) {
            float f = (float) size / mb;
            return String.format(f > 100 ? "%.0f MB" : "%.1f MB", f);
        } else if (size >= kb) {
            float f = (float) size / kb;
            return String.format(f > 100 ? "%.0f KB" : "%.1f KB", f);
        } else
            return String.format("%d B", size);
    }

    /**
     * 获取百分比
     *
     * @param pro
     * @param total
     * @return
     */
    public static String getPercentag(int pro, int total) {

        String baifenbi = "";// 接受百分比的值
        double baiy = pro * 1.0;
        double baiz = total * 1.0;
        double fen = baiy / baiz;
        // NumberFormat nf = NumberFormat.getPercentInstance();注释掉的也是一种方法
        // nf.setMinimumFractionDigits( 2 ); 保留到小数点后几位
        //DecimalFormat df1 = new DecimalFormat("##%");
        // ##.00%
        // 百分比格式，后面不足2位的用0补齐
        // baifenbi=nf.format(fen);
        baifenbi = precentDf.format(fen);
        return baifenbi;
    }

    public static DecimalFormat precentDf = new DecimalFormat("##%");

    public static final boolean isChinese(String strName) {
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(strName);
        if (m.find()) {
            return true;
        }
        return false;
    }


    /**
     * 是否能加载更多
     *
     * @param list     返回的数据
     * @param pageSize 每一页请求的值
     * @return
     */
    public static boolean isCanLoaderMore(List list, int pageSize) {

        if (list == null) {
            return false;
        }

        if (list.size() < pageSize) {
            return false;
        } else {
            return true;
        }
    }

    public static boolean isCanLoaderMore(List list, long pageSize) {

        if (list == null) {
            return false;
        }

        if (list.size() < pageSize) {
            return false;
        } else {
            return true;
        }
    }

    private static DecimalFormat priceFormat = new DecimalFormat("#0.00");

    public static String getPrice(long price) {
        float p = (float) (price / 1);
        return priceFormat.format(p);
    }

    public static String getPriceForYuan(long price) {
        float p = (float) (price / 100.00);
        return priceFormat.format(p);
    }

    /**
     * utf-8 转换成 unicode
     *
     * @param inStr
     * @return
     * @author fanhui
     * 2007-3-15
     */
    public static String utf8ToUnicode(String inStr) {
        char[] myBuffer = inStr.toCharArray();

        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < inStr.length(); i++) {
            Character.UnicodeBlock ub = Character.UnicodeBlock.of(myBuffer[i]);
            if (ub == Character.UnicodeBlock.BASIC_LATIN) {
                //英文及数字等
                sb.append(myBuffer[i]);
            } else if (ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
                //全角半角字符
                int j = (int) myBuffer[i] - 65248;
                sb.append((char) j);
            } else {
                //汉字
                short s = (short) myBuffer[i];
                String hexS = Integer.toHexString(s & 0xffff);
                String unicode = "\\u" + hexS;
                sb.append(unicode.toLowerCase());
            }
        }
        return sb.toString();
    }

    /**
     * unicode 转换成 utf-8
     *
     * @param theString
     * @return
     * @author fanhui
     * 2007-3-15
     */
    private static String unicodeToUtf8(String theString) {
        char aChar;
        int len = theString.length();
        StringBuffer outBuffer = new StringBuffer(len);
        for (int x = 0; x < len; ) {
            aChar = theString.charAt(x++);
            if (aChar == '\\') {
                aChar = theString.charAt(x++);
                if (aChar == 'u') {
                    // Read the xxxx
                    int size = theString.indexOf('\\', x) - x;
                    if (size < 0) {
                        size = len - x;
                    }
//                    LogUtils.d("size=" + size);
                    int value = 0;
                    for (int i = 0; i < size; i++) {
                        aChar = theString.charAt(x++);
                        switch (aChar) {
                            case '0':
                            case '1':
                            case '2':
                            case '3':
                            case '4':
                            case '5':
                            case '6':
                            case '7':
                            case '8':
                            case '9':
                                value = (value << 4) + aChar - '0';
                                break;
                            case 'a':
                            case 'b':
                            case 'c':
                            case 'd':
                            case 'e':
                            case 'f':
                                value = (value << 4) + 10 + aChar - 'a';
                                break;
                            case 'A':
                            case 'B':
                            case 'C':
                            case 'D':
                            case 'E':
                            case 'F':
                                value = (value << 4) + 10 + aChar - 'A';
                                break;
                            default:
                                break;
                        }
                    }
                    outBuffer.append((char) value);
                } else {
                    if (aChar == 't')
                        aChar = '\t';
                    else if (aChar == 'r')
                        aChar = '\r';
                    else if (aChar == 'n')
                        aChar = '\n';
                    else if (aChar == 'f')
                        aChar = '\f';
                    outBuffer.append(aChar);
                }
            } else
                outBuffer.append(aChar);
        }
        return outBuffer.toString();
    }

    /**
     * 将分钟数 转换为xiaoshi
     *
     * @param minute
     * @return
     */
    public static String getHour2String(int minute) {
        if (minute == 0) {
            return "0";
        }
        String hours;
        int hour = minute / 60;
        int dot = Math.round(minute % 60 / 6);
        hours = hour + "." + dot;
        return hours;
    }

    /**
     * 获取一个字符串的ascii码值
     *
     * @param str
     * @return
     */
    public static int stringToAscII(String str) {//字符串转换为ASCII码
        int length = 0;

        if (!isNoEmpty(str)) {
            return length;
        }
        char[] chars = str.toCharArray(); //把字符中转换为字符数组
        for (int i = 0; i < chars.length; i++) {//输出结果
            length += chars[i];
        }

        return length;
    }

    /**
     * 验证字符串中是否包含中文或特殊字符
     *
     * @param str
     * @return
     */
    public static boolean checkCharAscII(String str) {
        if (!isNoEmpty(str)) {
            return false;
        }
        char[] chars = str.toCharArray(); //把字符中转换为字符数组
        for (int i = 0; i < chars.length; i++) {//输出结果
            if (chars[i] > 127 || chars[i] < 32) {
                return false;
            }
        }

        return true;
    }

    /**
     * 获取一个字符串占几个字节
     *
     * @param str
     * @return
     */
    public static int getLength(String str) {//字符串转换为ASCII码
        int length = 0;

        if (!isNoEmpty(str)) {
            return length;
        }
        char[] chars = str.toCharArray(); //把字符中转换为字符数组
        for (int i = 0; i < chars.length; i++) {//输出结果
            if (chars[i] > 127 || chars[i] < 32) {
                length += 2;
            } else {
                length++;
            }
        }

        return length;
    }


    /**
     * 手机号用****号隐藏中间数字
     *
     * @param phone
     * @return
     */
    public static String settingphone(String phone) {
        String phone_s = phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
        return phone_s;
    }
}
